// Proxy 对象
const person = {
  name: "lagou",
  age: 20,
};
const personProxy = new Proxy(person, {
  get(target, property) {
    console.log(target, property); //{ name: 'lagou', age: 20 } name
    // return 100;
    return property in target ? target[property] : "default";
  },
  set(target, property, value) {
    if (property === "age") {
      if (!Number.isInteger(value)) {
        throw new TypeError(`${value} is not a int`);
      }
    }
    target[property] = value;
    // console.log(target, property, value); //{ name: 'lagou', age: 20 } gender true
  },
});
personProxy.gender = true;
personProxy.age = 100;
console.log(personProxy.name); //lagou
console.log(personProxy.xxx); //default
console.log(personProxy.age); //100

const person1 = {
  name: "lagou",
  age: 20,
};
const person1Proxy = new Proxy(person1, {
  deleteProperty(target, property) {
    console.log("delete", property);
    delete target[property];
  },
});
delete person1Proxy.age;
console.log(person1); //delete age { name: 'lagou' }

const list = [];
const listProxy = new Proxy(list, {
  set(target, property, value) {
    console.log("set", property, value);
    target[property] = value;
    return true; //表示设置成功
  },
});
listProxy.push(100);
console.log(list); // set 0 100 set length 1 [ 100 ]

const person2 = {};
Object.defineProperty(person2, "name", {
  get() {
    console.log("name被访问");
    return person2._name;
  },
  set(value) {
    console.log("name被设置");
    person2._name = value;
  },
});
person2.name = "lagou"; //name被设置
console.log(person2.name); //name被访问 lagou
console.log(person2); //{ _name: 'lagou' }

const obj = {
  foo: "123",
  bar: "456",
};
const proxy = new Proxy(obj, {
  //如果自己不定义get方法，默认return Reflect.get(target,property)
  get(target, property) {
    //定义了get则在get中添加需要的监视逻辑，最后返回默认需要返回的
    return Reflect.get(target, property);
  },
});

const obj1 = {
  name: "lagou",
  age: 10,
};
// console.log("name" in obj1);
// console.log(delete obj1[age]);
// console.log(Object.keys(obj1));
console.log(Reflect.has(obj1, "name"));
console.log(Reflect.deleteProperty(obj1, "age"));
console.log(Reflect.ownKeys(obj1));
